package com.centsuse.my_redis.service.impl;

import com.centsuse.my_redis.es.entity.KnowledgeDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bobo
 */
@Service
public class KnowledgeAdvancedSearchServiceImpl {

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    public Page<KnowledgeDocument> searchKnowledges(String titleKeyword, Boolean isPublished, List<String> sourceSystems,
                                                Pageable pageable) {
        try {
            // 1. 构建查询条件（修复语法错误和空值处理）
            Criteria criteria = new Criteria();

            // 只有当titleKeyword不为空时才添加条件
            if (StringUtils.hasText(titleKeyword)) {
                criteria = criteria.and("knTitle").contains(titleKeyword);
            }

            // 只有当isPublished不为null时才添加条件
            if (isPublished != null) {
                criteria = criteria.and("isPublished").is(isPublished);
            }

            if (sourceSystems != null && !sourceSystems.isEmpty()) {
                criteria = criteria.and("sourceSystem").in(sourceSystems);
            }

            // 2. 创建查询并设置分页
            Query query = new CriteriaQuery(criteria).setPageable(pageable);

            // 3. 执行查询
            SearchHits<KnowledgeDocument> hits = elasticsearchOperations.search(query, KnowledgeDocument.class);

            // 4. 转换结果（修复SearchHitSupport问题）
            List<KnowledgeDocument> content = hits.stream()
                    .map(SearchHit::getContent)
                    .collect(Collectors.toList());

            return new PageImpl<>(content, pageable, hits.getTotalHits());

        } catch (Exception e) {
            // 记录详细错误信息
            throw new RuntimeException("搜索失败，请检查Elasticsearch服务状态", e);
        }
    }
}